package main

import (
	"context"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

var (
	server   *http.Server
	listener net.Listener
)

// GraceRun 软启动
func GraceRun(port string, handler http.Handler) {
	log.Println("grace run")

	server = &http.Server{Addr: port, Handler: handler}
	log.Printf("Listening and serving HTTP on %s\n", port)

	var err error
	listener, err = net.Listen("tcp", server.Addr)

	if err != nil {
		log.Errorf("GraceRun Err: %v \n", err)
	}

	go func() {
		err = server.Serve(listener)
		if err == http.ErrServerClosed {
			log.Printf("server closed \n")
			removePidFile()
			os.Exit(0)
		} else {
			log.Panicf("server.Serve err: %v \n", err)
		}
	}()

	listenSignal()
	log.Printf("server quit bye")
}

// ListenSignal 监听系统信号,并做出操作.仅支持linux系统
func listenSignal() {
	ch := make(chan os.Signal, 1)
	listenList := []os.Signal{
		syscall.SIGINT,
		syscall.SIGTERM,
	}
	signal.Notify(ch, listenList...)

	var err error

	for {
		sig := <-ch
		log.Printf("signal: %v \n", sig)
		// ctx, _ := context.WithTimeout(context.Background(), time.Second*20)
		ctx := context.Background()
		switch sig {
		case syscall.SIGINT, syscall.SIGTERM:
			log.Printf("start stop \n")
			signal.Stop(ch)
			err = server.Shutdown(ctx)
			if err != nil {
				log.Printf("shutdown err: %v \n", err)
			}
			log.Println("graceful shutdown")
			return
		}
	}
}
